package com.anysoft.login;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.OpenSignFingerprintConfirmBean;
import com.anysoft.bean.UserBean;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.view.FingerPrinterView;
import com.anysoft.view.dialog.DialogUtils;
import com.anysoft.view.dialog.IcbcDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.os.Build.VERSION_CODES.M;

/**
 * Created by wwq on 2017/1/18.
 */

public class SetFingerPrintActivity extends BaseActivity {


    @BindView(R.id.tv_pass)
    TextView tvPass;
    @BindView(R.id.ll_login_pwd_bottom)
    LinearLayout llLoginPwdBottom;
    @BindView(R.id.tv_set_gesture)
    TextView tvSetGesture;
    @BindView(R.id.ll_login_pwd_top)
    LinearLayout llLoginPwdTop;
    @BindView(R.id.fpv)
    FingerPrinterView fpv;
    @BindView(R.id.iv_finger)
    ImageView ivFinger;

    private int fingerErrorNum = 0; // 指纹错误次数

    private FingerprintManager manager;//访问指纹硬件的类
    private KeyguardManager keyManager;//管理锁屏的类
    private CancellationSignal signal;
    //此类基于Java加密API的一个包装类,用于防止在指纹扫描中被第三方恶意攻击
    private FingerprintManager.CryptoObject cryptoObject;
    private static final int REQUST_CODE = 1;

    private String pwd = "";
    private UserBean userBean;

    private IcbcDialog fingerPrintDialog;
    private IcbcDialog fialeIcbcDialog;

    /**
     * 是否是来自指纹错误
     */
    private boolean isFromFaile = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_set_finger_print);
        ButterKnife.bind(this);

        pwd = getIntent().getStringExtra(MentorConst.GET_PASSWORD);
        userBean = (UserBean) getIntent().getSerializableExtra(MentorConst.GET_USERBEAN);

        fpv.setOnStateChangedListener(new FingerPrinterView.OnStateChangedListener() {
            @Override
            public void onChange(int state) {
                if (state == FingerPrinterView.STATE_CORRECT_PWD) {
                    fingerErrorNum = 0;
//                    Toast.makeText(SetFingerPrintActivity.this, "指纹识别成功", Toast.LENGTH_SHORT).show();
                }
                if (state == FingerPrinterView.STATE_WRONG_PWD) {
//                    Toast.makeText(SetFingerPrintActivity.this, "指纹识别失败，还剩" + (5 - fingerErrorNum) + "次机会",
//                            Toast.LENGTH_SHORT).show();
                    fpv.setState(FingerPrinterView.STATE_NO_SCANING);
                }
            }
        });

        minSdkVersion = Build.VERSION.SDK;
        if (Double.parseDouble(minSdkVersion) >= 23) {
            initFingerPrint();
        } else {
            initLowSDK();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initFingerPrint() {
        initFinger();
        if (isFingerprint()) {
            startListen();
        }

        fingerPrintDialog = new IcbcDialog(this);
        fingerPrintDialog.setAnimationEnable(true);
        fingerPrintDialog.setCancelable(false);
        fingerPrintDialog.setTitle("指纹验证");
        fingerPrintDialog.setContentText("请设置XXXXXX登录指纹");
        fingerPrintDialog.setContentImage(getResources().getDrawable(R.mipmap.finger_red));
        fingerPrintDialog.setPositiveListener("取消", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();

                if (signal != null) {
                    signal.cancel();
                    signal = null;
                }
            }
        }).show();
    }

    private void initLowSDK() {
        fingerPrintDialog.dismiss();

        showConfirmAlert(mActivity, "温馨提示", "目前指纹识别只支持6.0以上的系统哦!");
    }


    /**
     * 获得系统服务对象的引用
     */
    private void initFinger() {
        //通过V4包获得对象
        manager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
        keyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        signal = new CancellationSignal();

    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean isFingerprint() {
        //此方法为了保证判断是否支持支持指纹不报错
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getBaseContext(), "没有指纹解锁的权限", Toast.LENGTH_SHORT).show();
            return false;
        }
        //硬件设备是否支持指纹解锁功能
        if (!manager.isHardwareDetected()) {
            Toast.makeText(getBaseContext(), "该手机不支持指纹解锁", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否有锁屏密码
        if (!keyManager.isKeyguardSecure()) {
            Toast.makeText(getBaseContext(), "请设置锁屏密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否录入指纹
        if (!manager.hasEnrolledFingerprints()) {
            Toast.makeText(getBaseContext(), "没有录入指纹", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 开始指纹识别
     */
    @TargetApi(M)
    private void startListen() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        fpv.setState(FingerPrinterView.STATE_SCANING);

        FingerprintManager.AuthenticationCallback callBack = new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
//                Toast.makeText(getBaseContext(), "操作过于频繁,请稍后再试" + errString, Toast.LENGTH_SHORT).show();
                Logger.t("onAuthenticationError").d(errString.toString());

                if (!isFromFaile) {
                    if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                        fingerPrintDialog.dismiss();
                    }

                    if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                        fialeIcbcDialog.dismiss();
                    }
                    fialeIcbcDialog = new IcbcDialog(mActivity);
                    fialeIcbcDialog.setAnimationEnable(true);
                    fialeIcbcDialog.setCancelable(false);
                    fialeIcbcDialog.setTitle("指纹验证");
                    fialeIcbcDialog.setContentText(errString.toString());
                    fialeIcbcDialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();

                            if (signal != null) {
                                signal.cancel();
                                signal = null;
                            }
                        }
                    }).show();
                } else {
                    isFromFaile = false;
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                super.onAuthenticationHelp(helpCode, helpString);
                Logger.t("onAuthenticationHelp").d(helpString.toString());
            }

            //指纹识别成功
            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Logger.t("onAuthenticationSucceeded").d(result.toString());
                fpv.setState(FingerPrinterView.STATE_CORRECT_PWD);

                if (TextUtils.isEmpty(pwd)) {
                    showToast("缺少密码参数~");
                    return;
                }
                internetOpen();
            }

            //指纹识别失败
            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                if (fingerPrintDialog != null && fingerPrintDialog.isShowing()) {
                    fingerPrintDialog.dismiss();
                }

                if (fialeIcbcDialog != null && fialeIcbcDialog.isShowing()) {
                    fialeIcbcDialog.dismiss();
                }

                fpv.setState(FingerPrinterView.STATE_WRONG_PWD);

                if (fingerErrorNum == MentorConst.GESTURE_OR_FINGERPRINT_FAIL_TIMES) {
                    isFromFaile = true;
                    if (signal != null) {
                        signal.cancel();
                        signal = null;
                    }
                    DialogUtils utils = new DialogUtils();
                    utils.contentAlert(mActivity, "提示", "您已连续输入指纹错误，请跳过此步", "确定", "");
                    utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                        @Override
                        public void OnContentDialogSbtnClick() {
                            finish();
                        }
                    });
                } else {
                    fingerPrintDialog = new IcbcDialog(mActivity);
                    fingerPrintDialog.setAnimationEnable(true);
                    fingerPrintDialog.setCancelable(false);
                    fingerPrintDialog.setTitle("再试一次");
                    fingerPrintDialog.setContentText("请设置XXXXXX登录指纹");
                    fingerPrintDialog.setNegativeListener("确定", new IcbcDialog.OnNegativeListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();
                        }
                    });
                    fingerPrintDialog.setPositiveListener("取消", new IcbcDialog.OnPositiveListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();

                            if (signal != null) {
                                signal.cancel();
                                signal = null;
                            }
                        }
                    }).show();
                }
            }
        };
        manager.authenticate(cryptoObject, signal, 0, callBack, null);
    }

    private void internetOpen() {
        showLoading(mActivity);
        Map<String, String> params = new HashMap<>();
        params.put("tradePassword", pwd);
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("loginState", "1");//开启或者修改的内容 	1指纹  2手势
        params.put("fingerprintKey", getLocalSecretKey(mActivity, mentorApplication.userBean.getUserId()));
        params.put("signKey", "");
        String randomKey = "";
        for (int i = 0; i < 6; i++) {
            randomKey += String.valueOf((int) (Math.random() * 10));
        }
        final String randomFKey = HttpUtils.getMD5(getUUID() + randomKey);
        params.put("randomKey", randomFKey);
        params.put("mobileStyle", Build.MANUFACTURER);

        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.LOGIN, params));
        OkGo.<String>post(HostConstant.OPEN_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateInternetOpen(response.body(),randomFKey);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                        hideLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateInternetOpen(String json, String randomFKey) {
        hideLoading();
        OpenSignFingerprintConfirmBean bean;
        try {
            bean = new Gson().fromJson(json, OpenSignFingerprintConfirmBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        userBean.setIsFingerPrintOpen(true);
        updateFingerPrint(userBean, randomFKey);

        finish();

    }

    @OnClick({R.id.tv_pass, R.id.iv_finger})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pass:
                finish();
                break;
            case R.id.iv_finger:
                initFingerPrint();
                break;
        }
    }
}
